package erp

import (
	"context"
	"strconv"
	"strings"

	"mall/common/errorx"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/rpc/backendclient"
	"mall/service/order/rpc/orderclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type SyncOrderStatusToLocalLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 库存同步
func NewSyncOrderStatusToLocalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SyncOrderStatusToLocalLogic {
	return &SyncOrderStatusToLocalLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SyncOrderStatusToLocalLogic) SyncOrderStatusToLocal(req *types.SyncOrderStatusFromErpReq) (resp *types.BaseMsgResp, err error) {
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, errorx.Error(errorx.ERROR_TOKEN_EXPIRE, "")
	}

	orderList, err := l.svcCtx.BackendRpc.BackendGetErpOrderStatusList(l.ctx, &backendclient.GetErpOrderStatusListReq{
		ShopNick:  pointy.GetPointer(l.svcCtx.Config.Erp.ShopNick),
		TradeIds:  req.TradeIds,
		UpdatedBy: pointy.GetPointer(userId),
	})
	if err != nil {
		return nil, err
	}

	if len(orderList.List) == 0 {
		return nil, nil
	}

	var skusMap = map[string][]string{}
	for _, v := range orderList.List {
		if v != nil {
			if v.Status != nil && len(strings.TrimSpace(*v.Status)) > 0 && v.OrderSn != nil && len(strings.TrimSpace(*v.OrderSn)) > 0 {
				skusMap[*v.Status] = append(skusMap[*v.Status], *v.OrderSn)
			}
		}
	}
	if len(skusMap) > 0 {
		for i, v := range skusMap {
			if len(v) > 0 {
				status, _ := strconv.ParseUint(i, 10, 32)
				_, err = l.svcCtx.OrderRpc.BackendErpSetOrderStatus(l.ctx, &orderclient.ErpSetOrderStateReq{
					OrderSns:   pointy.GetPointer(strings.Join(v, ",")),
					TradeState: pointy.GetPointer(uint32(status)),
					UpdatedBy:  pointy.GetPointer(userId),
				})
				if err != nil {
					return nil, err
				}
			}
		}
	}
	return &types.BaseMsgResp{
		Msg: "同步成功",
	}, nil
}
